#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
unordered_map<int, int> index;
TreeNode *build_tree(const vector<int> &preorder, const vector<int> &inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right)
{
    if (preorder_left > preorder_right)
        return nullptr;
    int preorder_root = preorder_left;
    int inorder_root = index[preorder[preorder_root]];
    TreeNode *root = new TreeNode(preorder[preorder_root]);
    int size_left = inorder_root - inorder_left;
    root->left = build_tree(preorder, inorder, preorder_left + 1, preorder_left + size_left, inorder_left, inorder_root - 1);
    root->right = build_tree(preorder, inorder, preorder_left + size_left + 1, preorder_right, inorder_root + 1, inorder_right);
    return root;
}

vector<int> levelPrintTree(vector<int> &pre, vector<int> &mid)
{
    int n = pre.size();
    for (int i = 0; i < n; ++i)
    {
        index[mid[i]] = i;
    }
    TreeNode *root = build_tree(pre, mid, 0, n - 1, 0, n - 1);
    queue<TreeNode *> q;
    vector<int> res;
    if (root == nullptr)
        return res;
    q.push(root);
    while (!q.empty())
    {
        int sz = q.size();
        for (int i = 0; i < sz; ++i)
        {
            TreeNode *cur = q.front();
            q.pop();
            res.push_back(cur->val);
            if (cur->left != nullptr)
                q.push(cur->left);
            if (cur->right != nullptr)
                q.push(cur->right);
        }
    }
    return res;
}